"""
将 SVG 图标转换为 ICO 格式
简化版本：使用在线工具或手动转换
Windows 上 cairosvg 需要系统库，安装复杂，所以提供简化方案
"""
import sys
from pathlib import Path

# Try to use simpler method first
try:
    from PIL import Image
    HAS_PIL = True
except ImportError:
    HAS_PIL = False
    print("[WARN] Pillow not installed, will provide manual conversion instructions")

# Try cairosvg, but don't fail if not available
HAS_CAIRO = False
try:
    import cairosvg
    HAS_CAIRO = True
except ImportError:
    pass

def svg_to_ico_simple(svg_path, ico_path, sizes=[16, 32, 48, 64, 128, 256]):
    """简化版：将 SVG 转换为 ICO（需要 cairosvg 或手动转换）"""
    import io
    
    if not HAS_CAIRO:
        print("[ERROR] cairosvg not available (requires system libraries on Windows)")
        print("[INFO] Please convert SVG to ICO manually using online tools:")
        print("       https://convertio.co/zh/svg-ico/")
        print("       https://cloudconvert.com/svg-to-ico")
        print(f"       Input file: {svg_path}")
        print(f"       Output file: {ico_path}")
        return False
    
    if not HAS_PIL:
        print("[ERROR] Pillow not installed")
        print("Run: pip install Pillow")
        return False
    
    try:
        print(f"Converting {svg_path} -> {ico_path}...")
        
        # Read SVG and convert to PNG (max size)
        max_size = max(sizes)
        png_data = cairosvg.svg2png(url=str(svg_path), output_width=max_size, output_height=max_size)
        
        # Create PIL Image
        img = Image.open(io.BytesIO(png_data))
        
        # Create multi-size icon
        ico_images = []
        for size in sizes:
            resized = img.resize((size, size), Image.Resampling.LANCZOS)
            ico_images.append(resized)
        
        # Save as ICO
        ico_images[0].save(
            ico_path,
            format='ICO',
            sizes=[(s, s) for s in sizes]
        )
        
        print(f"[OK] ICO icon created: {ico_path}")
        print(f"    Sizes: {', '.join(map(str, sizes))}")
        return True
    except Exception as e:
        print(f"[ERROR] Conversion failed: {e}")
        print("[INFO] Please convert SVG to ICO manually using online tools")
        return False

if __name__ == "__main__":
    import io
    
    script_dir = Path(__file__).parent
    svg_file = script_dir / "sihe-icon.svg"
    ico_file = script_dir / "sihe-icon.ico"
    
    if not svg_file.exists():
        print(f"❌ 找不到 SVG 文件: {svg_file}")
        sys.exit(1)
    
    if svg_to_ico_simple(svg_file, ico_file):
        print("\n[SUCCESS] Icon created! You can now run create_shortcut.ps1")
    else:
        print("\n[INFO] Please convert SVG to ICO manually, then run create_shortcut.ps1 again")
        sys.exit(1)

